<?php
/*
Copyright (C) 2011  Benjamin Marchand

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

class PluginsController extends AppController {
	var $name = "Plugins";
	var $helpers = array('Html','Javascript','Session','Js' => array('jquery'));
	var $components = array('RequestHandler','Spyc','sfyaml');
	var $uses=array('mctemplateplugin','Setting','User','Item');
	
	function showconfig($name=NULL)
	{
		$this->autoLayout = FALSE;
		if (!empty($name))
		{
			$name = urldecode($name);
			$data = $this->mctemplateplugin->find('first',array('conditions'=>array('name LIKE'=>'%'.$name.'%')));
			if (!empty($data))
			{
				$this->set('config',$this->dumpConfig($data['mctemplateplugin']['config']));
				$this->set('id',$data['mctemplateplugin']['id']);
				$this->set('backup',$this->_getbackuplist($data['mctemplateplugin']['name']));
			}
			else
			{
				$this->set('data','Please define the plugin in the config tab.');
			}
		}
	}
	
	// name = name of the plugin
	function _getbackuplist($name)
	{
		$data="";
		$path = Configure::read('bukkitadmin.MinecraftPath');
		$backuppath = $path.DS.'WebBukkitBackup';
		if (file_exists($backuppath))
		{
			foreach (glob($backuppath.DS.$name."*") as $filename) {
				$filename = substr( $filename, ( strrpos( $filename, DS ) +1 ) );
				// extract the timestamp
				// and convert to human readable
				$timestamp = substr( $filename, ( strrpos( $filename, '.' ) +1 ) );
				//$data[$filename] = $filename;
				$data[$filename] = date('Y-m-d h:i:s',$timestamp);
			}
			return $data;
		}
		else
		return NULL;
	}
	function beforeRender(){
		//reads the site-wide config values from the DB and puts them through the Configure::write method
		$this->layout="private";
		$theme = Configure::read('bukkitadmin.theme');
		if (!empty($theme))
		{
			$this->theme = $theme;
		}

	}
	
	function beforeFilter(){
		//reads the site-wide config values from the DB and puts them through the Configure::write method
		$this->Setting->getcfg();
	}
	
	function afterFilter(){
		//retrieves the site-wide configurations from Configure::read($key) and puts it back into the db if new
		$this->Setting->writecfg();
	}
	
	function dumpYAMLConfig($file)	
	{
		$file = file_get_contents($file);
		$data = $this->Spyc->YAMLLoad($file);
		return $data;
	}
	
	function dumpConfig($file)	
	{
		$path = Configure::read('bukkitadmin.MinecraftPath');
		if (file_exists($path.$file))
		{
			$data = file_get_contents($path.$file);
		}
		else
		{	
			$data = 'Config file not exist !';
		}
		return utf8_encode($data);
	}
	
	function getVersion($file)
	{
		$path = Configure::read('bukkitadmin.MinecraftPath');
		$path.='plugins';
		$zip = new ZipArchive;
		if ($zip->open($path.DS.'BukkitTcpServer.jar') == TRUE)
		{
			$zip->extractTo(sys_get_temp_dir(),$file);
			$zip->close();
			$file = file_get_contents(sys_get_temp_dir().DS.$file);
			$data = $this->Spyc->YAMLLoad($file);
			return $data['version'];
		}
		else
		{
			return 'failed';
		}
	}
	
	function saveconfigplugin()
	{
		$this->autoRender = FALSE;
		$path = Configure::read('bukkitadmin.MinecraftPath');
		$backuppath = $path.DS.'WebBukkitBackup';
		if (!file_exists($backuppath))
			mkdir($backuppath);
		$data = $this->mctemplateplugin->findById($this->data['mctemplateplugin']['id']);
		if (!empty($data))
		{
			// Get original data
			$oritext = file_get_contents($path.$data['mctemplateplugin']['config']);
			// set the file backup, name of the backup file = name of the plugin + timestamp
			$backupfile = $backuppath.DS.$data['mctemplateplugin']['name'].'.'.time();
			var_dump($backupfile);
			// Backup the file before
			if (file_put_contents($backupfile,$oritext))
			{
				// then save the file
				if (file_put_contents($path.$data['mctemplateplugin']['config'],utf8_decode($this->data['mctemplateplugin']['code'])))
				{
					$this->showconfig($data['mctemplateplugin']['name']);
					$this->render('showconfig');
				}
				else
				{
					echo "Error saving config file! (Maybe insufficient privilege?)";
				}
			}
			else
			{
				echo "Error saving backup file! (Maybe insufficient privilege ?)";
			}
		}
		else
		{
			echo "Error getting data!";
		}
	}
	
	function __searchPlugins()
	{
		$path = Configure::read('bukkitadmin.MinecraftPath');
		$path.='plugins';
		$dir = opendir($path);
		while (false !== ($file = readdir($dir))) {
			if (strpos($file, '.jar',1)) {
				$info = pathinfo($file);
				$arrFiles[]= basename($file,'.'.$info['extension']);
			}
			} 
		return $arrFiles;
	}
	
	function edit_plugins()
	{
		$this->autoLayout = FALSE;
		$path = Configure::read('bukkitadmin.MinecraftPath');
		if (empty($path) || (!file_exists($path.'plugins')))
		{
			//echo "Error in the path of Minecraft !";
			//$this->set('plugins',$result);
			$this->set('message',"Warning, you should configure Bukkit Web admin!");
			$this->set('url','view_config');
			$this->render(array('controller'=>'private','action'=>'index'));
		}
		else
		{
			// We looking for the plugins
			$plugins = $this->__searchPlugins();
			// browse the plugins list
			// if the plugin is know, check the info
			foreach($plugins as $plugin)
			{
				$data = $this->mctemplateplugin->find('first',array('conditions'=>array('name LIKE'=>'%'.$plugin.'%')));
				if (!empty($data))
				{
					$result[] = $data['mctemplateplugin'];
				}
			}
			// We add the default config file for Bukkit (server.properties and whitelist)
				$result[] = array('name'=>'Minecraft server','config'=>'server.properties');
			// if whitelist exist
			if (file_exists($path."whitelist"))
			{
				$result[] = array('name'=>'White list','config'=>'whitelist');
			}
			// if Remote Toolkit exist
			if (file_exists($path."Minecraft_RKit.jar"))
			{
				$result[] = array('name'=>'RemoteToolkit','config'=>'/toolkit/wrapper.properties');
			}
			$this->set('plugins',$result);
		}
	}
	
	function deleteBackup()
	{
		$this->autoRender = FALSE;
		$backup = $this->params['form']['file'];
		if (!empty($backup))
		{
			$path = Configure::read('bukkitadmin.MinecraftPath');
			$backuppath = $path.DS.'WebBukkitBackup';
			unlink($backuppath.DS.$backup);
		}
		$data = $this->mctemplateplugin->findById($this->params['form']['id']);
		$this->showconfig($data['mctemplateplugin']['name']);
		$this->render('showconfig');
	}
	
	function selectBackup()
	{
		$this->autoRender = FALSE;
		$backup = $this->params['form']['file'];
		if (!empty($backup))
		{
			$path = Configure::read('bukkitadmin.MinecraftPath');
			$backuppath = $path.DS.'WebBukkitBackup';
			$oritext = file_get_contents($backuppath.DS.$backup);
			return utf8_encode($oritext);
		}
		else
		{
			$data = $this->mctemplateplugin->findById($this->params['form']['id']);
			return ($this->dumpConfig($data['mctemplateplugin']['config']));
		}
	}
	
	// function which return the groups inside Permissions plugin
	function getPPGroups()
	{
		//		var_dump($this->params['form']['world']);
		$this->autoRender = FALSE;
		$this->autoLayout = FALSE;
		// We get the config file for the Permission plugin Permission
		//$data = $this->mctemplateplugin->findByName('Permissions');
		if (!empty($this->params['form']['world']))
		{
			$world = $this->params['form']['world'];
			$path = Configure::read('bukkitadmin.MinecraftPath');
			$path .= DS.'plugins'.DS.'Permissions'.DS.$world;
			if (file_exists($path))
			{
				// We check if the file exist
				// If exist we parse the config file and get all groups
				// we send the list of group
				$data = $this->dumpYAMLConfig($path);
				$groups = array();
				foreach ($data['groups'] as  $key => $value)
				{
					$groups = array_merge($groups,array($key=>$key));
				}
				return json_encode($groups);
			}
		}
		return NULL;
	}
	
	function getPPUsers()
	{
		$this->autoRender = FALSE;
		$this->autoLayout = FALSE;
		$path = Configure::read('bukkitadmin.MinecraftPath');
		// We get the config file for the Permission plugin Permission
		$data = $this->mctemplateplugin->findByName('Permissions');
		if (!empty($data) && file_exists($path.$data['mctemplateplugin']['config']))
		{
			// We check if the file exist
			// If exist we parse the config file and get all groups
			// we send the list of group
			$data = $this->dumpYAMLConfig($path.$data['mctemplateplugin']['config']);
			$users = array();
			foreach ($data['users'] as  $key => $value)
			{
				$users[] = array('user'=>$key,'group'=>$value['group']);
			}
		}
		return $users;
	}
	
	// Function which display table with users data for a given world
	// Plugin : Group manager
	function showgmusers()
	{
		// we get the list of users
		$this->autoLayout = FALSE;
		$this->autoRender = FALSE;
		$index = 0;
		$world = $this->params['form']['world'];
		if (!empty($world))
		{
			$path = Configure::read('bukkitadmin.MinecraftPath');
			$path.= DS.'plugins'.DS.'GroupManager'.DS.'worlds'.DS.$world;
			// we read the config file
			//$data = $this->dumpYAMLConfig($path.DS.'groups.yml');
			$data = $this->sfyaml->load($path.DS.'users.yml');
			// we set the groups
			$nodes = $data['users'];
			foreach($nodes as $key => $values)
			{
				$users[$index]['name'] = $key;
				$users[$index]['group'] = $values['group'] ;
				$users[$index]['prefix'] = $values['info']['prefix'];
				$users[$index]['suffix'] = $values['info']['suffix'];
				//print_r($values);
				if (!empty($values['subgroups']))
				{
					foreach	($values['subgroups'] as $subgroups)
					{
						$users[$index]['subgroups'][] = $subgroups;
						}		
				}
				if(!empty($values['permissions']))
				{
					foreach	($values['permissions'] as $permission)
					{
						$users[$index]['permissions'][] = $permission;
					}
				}
				$index++;
			}
			$this->set('users',$users);
			$this->render('/elements/plugins_showgmusers');
			
		}
		//echo 'world : '.$this->params['form']['world'];
	}
	
	// Function which display table with groups data for a given world
	// parameter : the name of the world
	// Plugin : group manager
	function showgmgroups()
	{
		// we get the list of groups
		$this->autoLayout = FALSE;
		$this->autoRender = FALSE;
		$index = 0;
		$world = $this->params['form']['world'];
		if (!empty($world))
		{
			$path = Configure::read('bukkitadmin.MinecraftPath');
			$path.= DS.'plugins'.DS.'GroupManager'.DS.'worlds'.DS.$world;
			// we read the config file
			$data = $this->dumpYAMLConfig($path.DS.'groups.yml');
			//$data = $this->sfyaml->load($path.DS.'groups.yml');
			// we set the groups
			$nodes = $data['groups'];
			foreach($nodes as $key => $values)
			{
				$groups[$index]['name'] = $key;
				$groups[$index]['default'] = $values['default'] ;
				$groups[$index]['prefix'] = $values['info']['prefix'];
				$groups[$index]['suffix'] = $values['info']['suffix'];
				$groups[$index]['build'] = $values['info']['build'];
				//print_r($values);
				if (!empty($values['inheritance']))
				{
					foreach	($values['inheritance'] as $inheritances)
					{
						$groups[$index]['inheritance'][] = $inheritances;
						}		
				}
				if(!empty($values['permissions']))
				{
					foreach	($values['permissions'] as $permission)
					{
						$groups[$index]['permissions'][] = $permission;
					}
				}
				$index++;
			}
			$this->set('groups',$groups);
			$this->render('/elements/plugins_showgmgroups');
		}
	}
	
	// Function which display table with groups data for a given world
	// parameter : the name of the file
	// Plugin : permission
	function showpermgroups()
	{
		// we get the list of groups
		$this->autoLayout = FALSE;
		$this->autoRender = FALSE;
		$index = 0;
		$world = $this->params['form']['world'];
		if (!empty($world))
		{
			$path = Configure::read('bukkitadmin.MinecraftPath');
			$path.= DS.'plugins'.DS.'Permissions'.DS.$world;
			// we read the config file
			//var_dump($data);
			$data = $this->dumpYAMLConfig($path);
			//$data = $this->sfyaml->load($path);
			
			// we set the groups
			$nodes = $data['groups'];
			foreach($nodes as $key => $values)
			{
				$groups[$index]['name'] = $key;
				$groups[$index]['default'] = $values['default'] ;
				$groups[$index]['prefix'] = $values['info']['prefix'];
				$groups[$index]['suffix'] = $values['info']['suffix'];
				$groups[$index]['build'] = $values['info']['build'];
				if (!empty($values['inheritance']))
				{
					foreach	($values['inheritance'] as $inheritance)
					{
						$groups[$index]['inheritance'][] = $inheritance;
						}		
				}
				if(!empty($values['permissions']))
				{
					foreach	($values['permissions'] as $permission)
					{
						$groups[$index]['permissions'][] = $permission;
					}
				}
				$index++;
			}
			$this->set('groups',$groups);
			$this->render('/elements/plugins_showpermgroups');
		}
	}
	
	// Function which display table with users data for a given world
	// parameter : the name of the file
	// Plugin : permission
	function showpermusers()
	{
		// we get the list of groups
		$this->autoLayout = FALSE;
		$this->autoRender = FALSE;
		$index = 0;
		$world = $this->params['form']['world'];
		if (!empty($world))
		{
			$path = Configure::read('bukkitadmin.MinecraftPath');
			$path.= DS.'plugins'.DS.'Permissions'.DS.$world;
			// we read the config file
			$data = $this->dumpYAMLConfig($path);
			//$data = $this->sfyaml->load($path.DS.'groups.yml');
			// we set the groups
			$nodes = $data['users'];
			foreach($nodes as $key => $values)
			{
				$users[$index]['name'] = $key;
				$users[$index]['group'] = $values['group'] ;
				$users[$index]['prefix'] = $values['info']['prefix'];
				$users[$index]['suffix'] = $values['info']['suffix'];
				//print_r($values);
				if (!empty($values['subgroups']))
				{
					foreach	($values['subgroups'] as $subgroups)
					{
						$users[$index]['subgroups'][] = $subgroups;
						}		
				}
				if(!empty($values['permissions']))
				{
					foreach	($values['permissions'] as $permission)
					{
						$users[$index]['permissions'][] = $permission;
					}
				}
				$index++;
			}
			$this->set('users',$users);
			$this->render('/elements/plugins_showpermusers');
		}
	}
	
	// Display list of worlds in GroupManager dir
	function showgmworlds()
	{
		$path = Configure::read('bukkitadmin.MinecraftPath');
		$path.= DS.'plugins'.DS.'GroupManager'.DS.'worlds'.DS;
		if (file_exists($path))
		{
			foreach (glob($path."*",GLOB_ONLYDIR) as $filename) {
				$worlds[basename($filename)] = basename($filename);
			}
			return $worlds;
		}
		else
		{
			return FALSE;
		}
	}
	
	// Display list of worlds in Permissions plugin dir
	function showpermworlds()
	{
		$path = Configure::read('bukkitadmin.MinecraftPath');
		$path.= DS.'plugins'.DS.'Permissions';
		if (file_exists($path))
		{
			foreach (glob($path.DS."*.yml") as $filename) {
				$worlds[basename($filename)] = basename($filename);
			}
			return $worlds;
		}
		else
		{
			return FALSE;
		}
	}
	
	// Main function for GroupManager GUI
	function showgmgui()
	{
		$this->autoLayout = FALSE;
		$this->set('worlds',$this->showgmworlds());
	}
	
	// Main function for Permissions GUI
	function showguiperm()
	{
		$this->autoLayout = FALSE;
		$this->set('worlds',$this->showpermworlds());
	}
	
	// Main function for displaying plugins GUI
	function showgui()
	{
		$this->autoLayout = FALSE;
		$path = Configure::read('bukkitadmin.MinecraftPath');
		
		// If GM (GroupManager) plugin exist, we activate the GUI
		/*if (file_exists($path.DS.'plugins'.DS.'GroupManager.jar'))
		{
			$plugins[] = array('name'=>'Group Manager','action'=>'showgmgui');
			}*/
		// If Permissions plugin exist, we add it to the GUI
		
		if ($this->_pluginexist('Permissions'))
		{
			$plugins[] = array('name'=>'Permissions','action'=>'showguiperm');
		}
		/*if ($this->_pluginexist('Stats'))
		{
			$plugins[] = array('name'=>'Stats','action'=>'showstatgui');
			}*/
		if ($this->_pluginexist('Achievements'))
		{
			$plugins[] = array('name'=>'Achievements','action'=>'showguiach');
		}
		$this->set('itemsimages',$this->Item->find('list',array('fields'=>array('id','image'))));
		$this->set('plugins',$plugins);
	}
	
	// del groups in Permissions yml file
	// parameter : world and group name
	// Plugin : Permissions
	function delpermgroup()
	{
		$this->autoLayout = FALSE;
		$this->autoRender = FALSE;
		$grouptodel = $this->params['form']['group'];
		$world = $this->params['form']['world'];
		$path = Configure::read('bukkitadmin.MinecraftPath');
		$path.= DS.'plugins'.DS.'Permissions';
		// we read the config file
		$data = $this->dumpYAMLConfig($path.DS.$world);
		// we set the groups
		if (!empty($grouptodel) && !empty($world))
		{
			unset($data['groups'][$grouptodel]);
			// Put the save here
			file_put_contents($path.DS.$world,$this->Spyc->dump($data));
		}
		$this->showpermgroups();
	}
	
	// del users in Permissions yml file
	// parameter : world and user name
	// Plugin : Permissions
	function delpermuser()
	{
		$this->autoLayout = FALSE;
		$this->autoRender = FALSE;
		$usertodel = $this->params['form']['user'];
		$world = $this->params['form']['world'];
		$path = Configure::read('bukkitadmin.MinecraftPath');
		$path.= DS.'plugins'.DS.'Permissions';
		// we read the config file
		$data = $this->dumpYAMLConfig($path.DS.$world);
		// we set the groups
		if (!empty($usertodel) && !empty($world))
		{
			unset($data['users'][$usertodel]);
			// Put the save here
			file_put_contents($path.DS.$world,$this->Spyc->dump($data));
		}
		$this->showpermusers();
	}
	
	// Edit group in Permissions yml file
	// Plugin : Permissions
	function editpermgroup()
	{
		$name = $this->data['group']['name'];
		$build = ($this->data['group']['build']==0)?FALSE:TRUE;
		$default = ($this->data['group']['default']==0)?FALSE:TRUE;
		$suffix = $this->data['group']['suffix'];
		$prefix= $this->data['group']['prefix'];
		$world = $this->data['group']['world'];
		
		$permissions = preg_split('/\r\n|\r|\n/', $this->data['group']['permissions']);
		$inheritance = preg_split('/\r\n|\r|\n/',$this->data['group']['inheritance']);
		// Spyc quick fix for empty array
		if (empty($inheritance[0]))
		{
			$inheritance=NULL;
		}
		if (empty($permissions[0]))
		{
			$permissions=NULL;
		}
		
		$this->autoLayout = FALSE;
		$this->autoRender = FALSE;
		$yml['default'] = $default;
		$yml['inheritance']= $inheritance;
		$yml['permissions']= $permissions;
		$yml['info']['prefix'] = $prefix;
		$yml['info']['build'] = $build;
		$yml['info']['suffix'] = $suffix;
		
		$path = Configure::read('bukkitadmin.MinecraftPath');
		$path.= DS.'plugins'.DS.'Permissions';
		// we read the config file
		$data = $this->dumpYAMLConfig($path.DS.$world);
		// we del the node
		if (!empty($data['groups'][$name]))	unset($data['groups'][$name]);
		// and we add the new node
		$data['groups'][$name] = $yml;
		//file_put_contents($path.DS.$world,$this->sfyaml->dump($data));
		file_put_contents($path.DS.$world,$this->Spyc->dump($data));
		$this->params['form']['world'] = $world;
		$this->showpermgroups();
	}
	
	// Edit user in Permissions yml file
	// Plugin : Permissions
	function editpermuser()
	{
		$name = $this->data['user']['name'];
		$suffix = $this->data['user']['suffix'];
		$prefix= $this->data['user']['prefix'];
		$group = $this->data['user']['group'];
		$world = $this->data['user']['world'];
		
		$permissions = preg_split( '/\r\n|\r|\n/', $this->data['user']['permissions']);
		// Spyc quick fix for empty array
		if (empty($permissions[0]))
		{
			$permissions=NULL;
		}
		
		$this->autoLayout = FALSE;
		$this->autoRender = FALSE;
		$yml['group']= $group;
		$yml['info']['prefix'] = $prefix;
		$yml['info']['suffix'] = $suffix;
		$yml['permissions']= $permissions;
		
		$path = Configure::read('bukkitadmin.MinecraftPath');
		$path.= DS.'plugins'.DS.'Permissions';
		// we read the config file
		$data = $this->dumpYAMLConfig($path.DS.$world);
		// we del the node
		if (!empty($data['users'][$name])) unset($data['users'][$name]);
		// and we add the new node
		$data['users'][$name] = $yml;
		file_put_contents($path.DS.$world,$this->Spyc->dump($data));
		$this->params['form']['world'] = $world;
		$this->showpermusers();
		}	
	// del groups in Group Manager yml file
	// parameter : world and group name
	// Plugin : Group Manager
	function delgmgroup()
	{
		$this->autoLayout = FALSE;
		$this->autoRender = FALSE;
		$grouptodel = $this->params['form']['group'];
		$world = $this->params['form']['world'];
		$path = Configure::read('bukkitadmin.MinecraftPath');
		$path.= DS.'plugins'.DS.'GroupManager'.DS.'worlds'.DS.$world;
		// we read the config file
		$data = $this->dumpYAMLConfig($path.DS.'groups.yml');
		// we set the groups
		//$nodes = $data['groups'];
		if (!empty($grouptodel) && !empty($world))
		{
			unset($data['groups'][$grouptodel]);
			// Put the save here
			file_put_contents($path.DS.'groups.yml',$this->sfyaml->dump($data));
		}
		$this->showgmgroups();
	}
	
	// Edit group in Group Manager yml file
	function editmggroup()
	{
		$name = $this->data['group']['name'];
		$build = ($this->data['group']['build']==0)?'false':'true';
		$default = ($this->data['group']['default']==0)?'false':'true';
		$suffix = $this->data['group']['suffix'];
		$prefix= $this->data['group']['prefix'];
		$world = $this->data['group']['world'];
		
		//$permissions = $this->data['group']['permissions'];
		$permissions = preg_split( '/\r\n|\r|\n/', $this->data['group']['permissions']);
		$inheritance = preg_split('/\r\n|\r|\n/',$this->data['group']['inheritance']);
		
		$this->autoLayout = FALSE;
		$this->autoRender = FALSE;
		$yml['default'] = $default;
		$yml['inheritance']= $inheritance;
		$yml['permissions']= $permissions;
		$yml['info']['prefix'] = $prefix;
		$yml['info']['build'] = $build;
		$yml['info']['suffix'] = $suffix;
		
		$path = Configure::read('bukkitadmin.MinecraftPath');
		$path.= DS.'plugins'.DS.'GroupManager'.DS.'worlds'.DS.$world;
		// we read the config file
		$data = $this->dumpYAMLConfig($path.DS.'groups.yml');
		// we del the node
		if (!empty($data['groups'][$name]))	unset($data['groups'][$name]);
		// and we add the new node
		$data['groups'][$name] = $yml;
		file_put_contents($path.DS.'groups.yml',$this->sfyaml->dump($data));
		$this->params['form']['world'] = $world;
		$this->showgmgroups();
	}
	
	// Edit user in Group Manager yml file
	function editmguser()
	{
		$name = $this->data['user']['name'];
		$suffix = $this->data['user']['suffix'];
		$prefix= $this->data['user']['prefix'];
		$group = $this->data['user']['group'];
		$world = $this->data['user']['world'];
		
		//$permissions = $this->data['group']['permissions'];
		$permissions = preg_split( '/\r\n|\r|\n/', $this->data['user']['permissions']);
		$subgroup = preg_split('/\r\n|\r|\n/',$this->data['user']['subgroups']);
		
		$this->autoLayout = FALSE;
		$this->autoRender = FALSE;
		$yml['$subgroup']= $inheritance;
		$yml['permissions']= $permissions;
		$yml['group']= $group;
		$yml['info']['prefix'] = $prefix;
		$yml['info']['suffix'] = $suffix;
		
		$path = Configure::read('bukkitadmin.MinecraftPath');
		$path.= DS.'plugins'.DS.'GroupManager'.DS.'worlds'.DS.$world;
		// we read the config file
		$data = $this->dumpYAMLConfig($path.DS.'users.yml');
		// we del the node
		if (!empty($data['users'][$name]))	unset($data['users'][$name]);
		// and we add the new node
		$data['users'][$name] = $yml;
		file_put_contents($path.DS.'users.yml',$this->sfyaml->dump($data));
		$this->params['form']['world'] = $world;
		$this->showgmusers();
	}
	
	function editach()
	{
		$path = Configure::read('bukkitadmin.MinecraftPath');
		$path .= DS.'achievements'.DS.'achievements.txt';
		$ach = $this->data['ach']['active'].':'.$this->data['ach']['name'].':'.$this->data['ach']['maxarwards'].':'.$this->data['ach']['category'].':'.$this->data['ach']['key'].':'.$this->data['ach']['value'].':'.$this->data['ach']['description'].':';
		if (!empty($this->data['ach']['item']))
			$arr[] = 'item '.$this->data['ach']['item'].' '.$this->data['ach']['amount'];
		if (!empty($this->data['ach']['group']))
			$arr[] = 'group '.$this->data['ach']['group'];	
		if (!empty($this->data['ach']['money']))
			$arr[] = 'money '.$this->data['ach']['money'];
		$strarr = implode(';',$arr);
		$ach .= $strarr;
		if (!empty($this->data['ach']['listach']))
			$ach .= ':'.$this->data['ach']['listach'];
		$data = file_get_contents($path);
		$data = preg_split('/\r\n|\r|\n/',$data);
		if ($this->data['ach']['new']=='true')
		{
			file_put_contents($path, "\n".$ach."\n", FILE_APPEND);
		}
		else
		{
			file_put_contents($path,"");
			foreach($data as $lines)
			{
				$segments=explode(":",$lines);
				if ($segments[1]==$this->data['ach']['name'])
				{
					file_put_contents($path, $ach."\n", FILE_APPEND);
				}
				else
					file_put_contents($path, $lines."\n", FILE_APPEND);
			}
		}
		//echo $ach;
		$this->showguiach(0);
		$this->render('/elements/plugins_showach');
	}
	
	function showguiach($show=NULL)
	{
		$this->autoLayout=FALSE;
		if (empty($show)) $show=0;
		$path = Configure::read('bukkitadmin.MinecraftPath');
		// We set the items list
		if (file_exists($path.DS.'items.txt'))
		{
			$data = file_get_contents($path.DS.'items.txt');
			$data = preg_split('/\r\n|\r|\n/',$data);
			
			foreach($data as $item)
			{
				if (!preg_match("/^#/",$item) && (trim($item)!=''))
				{
					$objects[]=explode(":",$item);
				}
			}
			foreach($objects as $object)
			{
				if ($object[1]<256)
					$blocks[$object[0]]=$object[0];
				else
					$items[$object[0]]=$object[0];
			}
			asort($items);
			asort($blocks);
			$category = array(
			'blockcreate'=>'blockcreate',
			'blockdestroy'=>'blockdestroy',
			'damagedealt'=>'damagedealt',
			'damagetaken'=>'damagetaken',
			'deaths'=>'deaths',
			'itemdrop'=>'itemdrop',
			'itempickup'=>'itempickup',
			'itemuse'=>'itemuse',
			'kills'=>'kills',
			'stats'=>'stats'
			);
			$this->set('category',$category);
			$this->set('items',$items);
			$this->set('blocks',$blocks);
		}
		$path .= DS.'achievements'.DS.'achievements.txt';
		if (file_exists($path))
		{
			// We read the file 
			$data = file_get_contents($path);
			$data = preg_split('/\r\n|\r|\n/',$data);
			foreach($data as $ach)
			{
				if (!preg_match("/^#/",$ach) && (trim($ach)!=''))
				{
					$achs[]=explode(":",$ach);
				}
			}
			foreach($achs as $ach)
			{
				$listach[$ach[1]]=$ach[1];
			}
			asort($listach);
			$this->set('count',count($achs));
			$achs = array_slice($achs,$show*10,10);
			$this->set('achs',$achs);
			$this->set('listach',$listach);
			$this->set('show',$show);
		}
		else
		{
			$messages[] = array('image'=>'clear_icon.png','message'=>__('Achievements database (achievements.txt) not found!',true));
			$this->set('messages',$messages);
			$this->render('/elements/message');
		}
	}
	
	function _pluginexist($plugin)
	{
		$path = Configure::read('bukkitadmin.MinecraftPath');
		$path .= DS.'plugins'.DS.$plugin.'.jar';
		if (file_exists($path))
			return TRUE;
		else
		return FALSE;
	}
	
	function delach()
	{
		$this->autoLayout=FALSE;
		$path = Configure::read('bukkitadmin.MinecraftPath');
		$path .= DS.'achievements'.DS.'achievements.txt';
		if (file_exists($path))
		{
			// We read the file 
			$data = file_get_contents($path);
			$data = preg_split('/\r\n|\r|\n/',$data);
			file_put_contents($path,"");
			foreach($data as $ach)
			{
				$achs=explode(":",$ach);
				if ($achs[1]!=urldecode($this->params['form']['name']))
				{
					file_put_contents($path, $ach."\n", FILE_APPEND);
					//$output[] = $ach;
				}
			}
		}
		$this->showguiach(0);
		$this->render('/elements/plugins_showach');
	}
}
?>